#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
class WorklogsController < ApplicationController

#  layout "application"

  before_filter :authorize

  def index
    list
    render :action => 'list'
  end

  # FIXME don't we post to list ???
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    worker_id = session[:user_id]
    @user = User.find(worker_id)
    if request.get?
      @worklog = init_worklog(worker_id)
      # user_time to system_time
      @worklog.done_at = @user.tzget.utc_to_local(@worklog.done_at)
    else
      @worklog = Worklog.new(params[:worklog])
      # user_time to system_time
      @worklog.done_at = @user.tzget.local_to_utc(@worklog.done_at)
      if @worklog.save
        flash[:notice] = 'Worklog was successfully created.'
        @worklog = init_worklog(worker_id)
      end
    end
    if (@worklog.worker.is_not_assigned?)
      flash[:notice] = 'You cannot enter worklogs on any project. Assign yourself or get someone to assign you to one'
    end
    @worklog_pages, @worklogs = paginate :worklogs, :per_page => 10, 
                :select => "worklogs.*",
                :order => "done_at desc", 
                :joins => "LEFT OUTER JOIN assignments as a ON worklogs.assignment_id = a.id",
                :conditions => ["a.user_id = ?", worker_id]
  end

  def edit
    find_worklog
  end

  def update
    # FIXME security
    find_worklog
    if @worklog.update_attributes(params[:worklog])
      flash[:notice] = 'Worklog was successfully updated.'
      redirect_to :action => 'edit', :id => @worklog
    else
      render :action => 'edit'
    end
  end

  def destroy
    # FIXME security
    Worklog.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

  private
  def find_worklog
    @worklog = Worklog.find(params[:id])
  end

  def init_worklog(worker_id)
    worklog = Worklog.new
    worklog.done_at = DateTime.now
    worklog.assignment = Assignment.new
    worklog.assignment.user_id = worker_id
    worklog
  end

end
